//
//  NetworkMgr.m
//  ProfilePicture
//
//  Created by 张云江 on 2019/10/14.
//  Copyright © 2019年 张云江. All rights reserved.
//

#import "NetworkMgr.h"
#import "AFNetworking.h"

static NetworkMgr *nwMgr;

@implementation NetworkMgr

+ (id)shareInstance
{
    @synchronized (nwMgr) {
        if (!nwMgr) {
            nwMgr = [[NetworkMgr alloc] init];
        }
    }
    return nwMgr;
}

- (void)uploadImage:(NSData *)data
            withApi:(NSString *)api
     withParameters:(NSDictionary *)parameters
            success:(nullable void (^)(NSDictionary *result, int code))success
            failure:(nullable void (^)(NSError *error))failure
{
    NSString *base64Str = [data base64Encoding];
    
    NSData *base64Str_data = [base64Str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableDictionary *parameters_M = [[NSMutableDictionary alloc]init];
    
    [parameters_M setObject:base64Str forKey:[NSString stringWithFormat:@"file"]];
    [parameters_M setObject:kAppkey forKey:@"app_key"];
    [parameters_M addEntriesFromDictionary:parameters];
    
    NSString *url = [self URLEncodedString:[NSString stringWithFormat:@"%@%@",kBaseUrl,api]];
    NSString *parameters_Str = [self convertDictoryToJson:parameters_M];

    NSLog(@"url = %@",url);
    NSLog(@"parameters = %@",parameters_Str);
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    
    request.timeoutInterval = 60;
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[parameters_Str dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *returnJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            int code = [[returnJson objectForKey:@"code"] integerValue];
            NSLog(@"请求成功 code = %d -- result = %@",code,returnJson);
            if (success) {
                success(returnJson,code);
            }
            
        } else {
            NSLog(@"请求失败 -- %@ -- 错误码 = %d", api,error.code);
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}

- (void)uploadImage:(NSData *)data
            withApi:(NSString *)api
     withParameters:(NSDictionary *)parameters
            success:(nullable void (^)(NSDictionary *result, int code))success
            failure:(nullable void (^)(NSError *error))failure
         withAppkey:(NSString *)appkey
{
    NSString *base64Str = [data base64Encoding];
    
    NSData *base64Str_data = [base64Str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableDictionary *parameters_M = [[NSMutableDictionary alloc]init];
    
    [parameters_M setObject:base64Str forKey:[NSString stringWithFormat:@"file"]];
    [parameters_M setObject:appkey forKey:@"app_key"];
    [parameters_M addEntriesFromDictionary:parameters];
    
    NSString *url = [self URLEncodedString:[NSString stringWithFormat:@"%@%@",kBaseUrl,api]];
    NSString *parameters_Str = [self convertDictoryToJson:parameters_M];
    
    NSLog(@"url = %@",url);
    NSLog(@"parameters = %@",parameters_Str);
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    
    request.timeoutInterval = 60;
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[parameters_Str dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *returnJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            int code = [[returnJson objectForKey:@"code"] integerValue];
            NSLog(@"请求成功 code = %d -- result = %@",code,returnJson);
            if (success) {
                success(returnJson,code);
            }
            
        } else {
            NSLog(@"请求失败 -- %@ -- 错误码 = %d", api,error.code);
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}

- (void)postwithApi:(NSString *)api
     withParameters:(NSDictionary *)parameters
            success:(nullable void (^)(NSDictionary *result, int code))success
            failure:(nullable void (^)(NSError *error))failure
{
    NSMutableDictionary *parameters_M = [[NSMutableDictionary alloc]init];
    
    [parameters_M setObject:kAppkey forKey:@"app_key"];
    [parameters_M addEntriesFromDictionary:parameters];
    
    NSString *url = [self URLEncodedString:[NSString stringWithFormat:@"%@%@",kBaseUrl,api]];
    NSString *parameters_Str = [self convertDictoryToJson:parameters_M];
    
    NSLog(@"url = %@",url);
    NSLog(@"parameters = %@",parameters_Str);
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    
    request.timeoutInterval = 60;
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[parameters_Str dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *returnJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            int code = [[returnJson objectForKey:@"code"] integerValue];
            NSLog(@"请求成功 code = %d -- result = %@",code,returnJson);
            if (success) {
                success(returnJson,code);
            }
            
        } else {
            NSLog(@"请求失败 -- %@ -- 错误码 = %d", api,error.code);
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}

- (void)postwithApi:(NSString *)api
     withParameters:(NSDictionary *)parameters
            success:(nullable void (^)(NSDictionary *result, int code))success
            failure:(nullable void (^)(NSError *error))failure
         withAppkey:(NSString *)appkey
{
    NSMutableDictionary *parameters_M = [[NSMutableDictionary alloc]init];
    
    [parameters_M setObject:appkey forKey:@"app_key"];
    [parameters_M addEntriesFromDictionary:parameters];
    
    NSString *url = [self URLEncodedString:[NSString stringWithFormat:@"%@%@",kBaseUrl,api]];
    NSString *parameters_Str = [self convertDictoryToJson:parameters_M];
    
    NSLog(@"url = %@",url);
    NSLog(@"parameters = %@",parameters_Str);
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    
    request.timeoutInterval = 60;
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[parameters_Str dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
            NSDictionary *returnJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            int code = [[returnJson objectForKey:@"code"] integerValue];
            NSLog(@"请求成功 code = %d -- result = %@",code,returnJson);
            if (success) {
                success(returnJson,code);
            }
            
        } else {
            NSLog(@"请求失败 -- %@ -- 错误码 = %d", api,error.code);
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}

- (void)postwithImageName:(NSString *)imageName
                  success:(nullable void (^)(NSData *data))success
                  failure:(nullable void (^)(NSError *error))failure
{
    NSMutableDictionary *parameters_M = [[NSMutableDictionary alloc]init];
    
    if (WCDelegate.currClothes.length > 0) {
        [parameters_M setObject:kAppkey2 forKey:@"app_key"];
    } else {
        [parameters_M setObject:kAppkey forKey:@"app_key"];
    }
    [parameters_M setObject:imageName forKey:@"file_name"];
    
    NSString *url = [self URLEncodedString:[NSString stringWithFormat:@"%@%@",kBaseUrl,@"take_cut_pic"]];
    NSString *parameters_Str = [self convertDictoryToJson:parameters_M];
    
    NSLog(@"url = %@",url);
    NSLog(@"parameters = %@",parameters_Str);
    
    NSURL *ul = [NSURL URLWithString:url];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:ul];
    request.HTTPMethod = @"POST";
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    request.HTTPBody = [parameters_Str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"请求失败 -- 错误码 = %d",error.code);
                if (failure) {
                    failure(error);
                }
            } else {
                if (success) {
                    success(data);
                }
            }
        });
    }];
    [dataTask resume];
}

- (NSString *)URLEncodedString:(NSString *)resource
{
    resource = [resource stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    return resource;
}

- (NSString*)convertDictoryToJson:(NSMutableDictionary*)jsonDic
{
    NSData *posData;
    if ([NSJSONSerialization isValidJSONObject:jsonDic]) {
        posData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:posData encoding:NSUTF8StringEncoding];
        return jsonStr;
    }
    return @"";
}
@end
